﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using work_log.userservices;
using System.Threading;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using work_log.worklogservices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace work_log {
    public partial class frmLogs : DevExpress.XtraEditors.XtraForm {
        /// <summary>
        /// UI线程同步上下文
        /// </summary>
        SynchronizationContext mainContext = null;
        public frmLogs() {
            InitializeComponent();
            //获取UI线程同步上下文
            mainContext = SynchronizationContext.Current;
        }

        private void frmLogs_Load(object sender, EventArgs e) {
            this.gridView1.CustomDrawCell += gridView1_CustomDrawCell;
            this.gridView1.MouseDown += gridView1_MouseDown;
            this.gridView1.RowCellClick += gridView1_RowCellClick;
            this.gridView1.CustomDrawRowIndicator += gridView1_CustomDrawRowIndicator;
            this.gridView1.PopupMenuShowing += gridView1_PopupMenuShowing;

            //取消自适应大小时闪烁
            flowLayoutPanel1.GetType().GetProperty("DoubleBuffered", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic).SetValue(tableLayoutPanel1, true, null);

            this.gridView1.IndicatorWidth = 40;
            this.dtStart.Text = DateTime.Now.AddDays(-14).ToString("yyyy-MM-dd");
            this.dtEnd.Text = DateTime.Now.ToString("yyyy-MM-dd");

            this.pgWork.Visible = true;
        }

        #region Init
        /// <summary>
        /// 数据加载
        /// </summary>
        private void DataLoad() {
            try {
                WorkLogs entity = new WorkLogs();
                entity.wContent = this.txtContent.Text.Trim();
                entity.wTitle = this.txtTitle.Text.Trim();
                entity.User_uid = UserInfo.uid;
                ResultInfoOfWorkLogs result = new workLogServicesSoapClient().FindBy(entity, true, Convert.ToDateTime(this.dtStart.Text + " 00:00:00"), Convert.ToDateTime(this.dtEnd.Text + " 23:59:59"));
                if (result.Result) {
                    //DataTable dt = 
                    mainContext.Post(mainSafeOpertion, result.DataFormat);
                } else {
                    XtraMessageBox.Show(result.MSG);
                }
            } catch (Exception ex) {
                XtraMessageBox.Show(ex.Message);
            }
            mainContext.Post(mainSafeOpertion, null);
        }
        #endregion

        #region Thread Opertion
        /// <summary>
        /// 线程间的安全操作
        /// </summary>
        /// <param name="sender"></param>
        private void mainSafeOpertion(object sender) {
            if (sender != null) {
                MemoryStream ms = new MemoryStream((byte[])sender);
                IFormatter formatData = new BinaryFormatter();
                gridControl1.DataSource = (DataTable)formatData.Deserialize(ms);
            } else
                this.pgWork.Visible = false;
        }
        #endregion

        #region GridView
        void gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e) {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0) {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
            }
        }

        void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e) {
            if (e.RowHandle >= 0) {
                if (e.Column.ColumnEdit != null && e.Column.ColumnEdit.NullText == "查看文件") {
                    Guid wId = Guid.Parse(gridView1.GetRowCellValue(e.RowHandle, "wId").ToString());
                    if (wId != Guid.Parse("00000000-0000-0000-0000-000000000000")) {
                        WorkLogInfo.wId = wId;
                        frmFiles frm = new frmFiles();
                        frm.ShowDialog();
                    }
                }
            }
        }

        void gridView1_MouseDown(object sender, MouseEventArgs e) {
            GridHitInfo hInfo = gridView1.CalcHitInfo(new Point(e.X, e.Y));
            if (e.Button == System.Windows.Forms.MouseButtons.Left && e.Clicks == 2) {
                if (hInfo.InRow) {
                    Guid wId = Guid.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "wId").ToString());
                    if (wId != Guid.Parse("00000000-0000-0000-0000-000000000000")) {
                        WorkLogInfo.wId = wId;
                        frmAddLog frm = new frmAddLog();
                        DialogResult result = frm.ShowDialog();
                        if (result.ToString() == "OK" && !this.pgWork.Visible) {
                            this.pgWork.Visible = true;
                            Thread mainThread = new Thread(new ThreadStart(this.DataLoad));
                            mainThread.Start();
                        }
                    }
                }
            }
        }

        void gridView1_CustomDrawCell(object sender, DevExpress.XtraGrid.Views.Base.RowCellCustomDrawEventArgs e) {
            if (e.RowHandle >= 0) {
                if (e.Column.Name == "gridColumn8") {
                    Guid wId = Guid.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "wId").ToString());
                    if (wId != Guid.Parse("00000000-0000-0000-0000-000000000000")) {
                        gridView1.Columns[7].ColumnEdit.NullText = "查看文件";
                    }
                }
            }
        }

        void gridView1_PopupMenuShowing(object sender, DevExpress.XtraGrid.Views.Grid.PopupMenuShowingEventArgs e) {
            if (this.gridView1.RowCount == 1) {
                删除ToolStripMenuItem.Visible = false;
            } else {
                删除ToolStripMenuItem.Visible = true;
            }
        }
        #endregion

        private void frmLogs_Shown(object sender, EventArgs e) {
            Thread mainThread = new Thread(new ThreadStart(this.DataLoad));
            mainThread.Start();
        }

        private void btnAdd_Click(object sender, EventArgs e) {
            WorkLogInfo.wId = Guid.Empty;
            frmAddLog frm = new frmAddLog();
            DialogResult result = frm.ShowDialog();
            if (result.ToString() == "OK" && !this.pgWork.Visible) {
                this.pgWork.Visible = true;
                Thread mainThread = new Thread(new ThreadStart(this.DataLoad));
                mainThread.Start();
            }
        }

        private void btnSearch_Click(object sender, EventArgs e) {
            if (pgWork.Visible) {
                XtraMessageBox.Show("当前正在加载数据，请不要重复加载！");
            } else {
                this.pgWork.Visible = true;
                Thread mainThread = new Thread(new ThreadStart(this.DataLoad));
                mainThread.Start();
            }
        }

        private void 删除ToolStripMenuItem_Click(object sender, EventArgs e) {
            if (this.gridView1.RowCount > 0) {
                try {
                    Guid wId = Guid.Parse(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "wId").ToString());
                    if (wId != Guid.Parse("00000000-0000-0000-0000-000000000000")) {
                        if (XtraMessageBox.Show("是否确认删除？", "温馨提示：", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.OK) {
                            ResultInfoOfWorkLogs result = new workLogServicesSoapClient().Del(wId);
                            if (result.Result) {
                                XtraMessageBox.Show("删除成功！");
                                this.pgWork.Visible = true;
                                Thread mainThread = new Thread(new ThreadStart(this.DataLoad));
                                mainThread.Start();
                            } else {
                                XtraMessageBox.Show(result.MSG);
                            }
                        }
                    }
                } catch (Exception ex) {
                    XtraMessageBox.Show(ex.Message);
                }
            }
        }
    }
}